#include "test2.h"

status LinkNode_CreateHead(LinkNode *list,int n)
{
    LinkNode p;
    int i;
    srand(time(0));
    (*list) = (LinkNode)malloc(sizeof(LinkNode));
    (*list)->next = NULL;
    for(i = 0; i < n; i++){
        p = (LinkNode)malloc(sizeof(LinkNode));
        p->data = rand()%100+1;
        p->next = (*list)->next;
        (*list)->next = p;
    }
    return OK;
}

status LinkNode_Insert(LinkNode *list, int i, Elemtype data)
{
    int j=1;
    LinkNode p,s;
    if( (*list)->next==NULL || i<1 )
        return NO;
    p=*list;
    while(p!=NULL && j<i){
        p=p->next;
        ++j;
    }
    if( p==NULL || j>i)
        return NO;
    s = (LinkNode)malloc(sizeof(LinkNode));
    s->data = data;
    s->next=p->next;
    p->next=s;
    return OK;
}

status LinkNode_GetElem(LinkNode *list, int i, Elemtype *data)
{
    int j=0;
    LinkNode p = (*list);
    if( p==NULL || p->next==NULL || i<1)
        return NO;
    while(p->next!=NULL && j<i){
        p=p->next;
        j++;
    }
    
    *data = p->data;
    return OK;
}

status LinkNode_GetAllElem(LinkNode *list)
{
    LinkNode p;
    int i=1;
    p=(*list)->next;
    while(p!=NULL){
        printf("i=%d  data=%d\n",i++,p->data);
        p=p->next;
    }
    printf("\n");
}

status LinkNode_Delete(LinkNode *list, int i)
{
    LinkNode p,s;
    p = (*list);
    int j=1;
    if( p->next == NULL || i<1 )
        return NO;
    while(p->next!=NULL&j<i){
        p=p->next;
        j++;
    }
    s=p->next;
    p->next=s->next;
    free(s);
    return OK;
}

status LinkNode_FreeAll(LinkNode *list)
{
    LinkNode p,s;
    p = *list;
    do{
        s=p;
        p=p->next;
        printf("free %d\n",s->data);
        free(s);
    }while(p!=NULL);
}

status LinkNode_InsertTail(LinkNode *list, Elemtype data)
{
    LinkNode p,s;
    p=*list;
    while(p->next!=NULL){
        p=p->next;
        printf("%d\n",p->data);
    }
    s = (LinkNode)malloc(sizeof(LinkNode));
    s->data = data;
    s->next=NULL;
    p->next = s;
}

status LinkNode_RollBack(LinkNode *list)
{
    LinkNode p,s,r;
    if(list==NULL || (*list)->next->next==NULL)
        return NO;
    // 将链表分成两部分H->[]和Q->[]->[]->[]...
    p = *list;
    s = p->next->next;
    p->next->next=NULL;
    while (s!=NULL)
    {
        r = s;
        s = s->next;
        r->next = p->next;
        p->next = r;
    }
     return OK;   
}

void test2(void)
{
    LinkNode node;
    int data = 0;
    LinkNode_CreateHead(&node,5);
    LinkNode_GetAllElem(&node);
    // LinkNode_InsertTail(&node,666);
    // LinkNode_GetElem(&node,2,&data);
    // printf("data = %d\n",data);
    // LinkNode_Insert(&node,3,555);
    // LinkNode_Delete(&node,1);
    LinkNode_RollBack(&node);
    LinkNode_GetAllElem(&node);
    // LinkNode_FreeAll(&node);
    
}
